﻿using System.Windows;
using System.Xml;
using System.Xml.Serialization;

namespace Wix.Win8SetupBootstrapper.Classes.Configuration
{
    internal static class ConfigurationLoader
    {
        private static XmlDocument _doc;
        private static XmlNamespaceManager _nsmgr;
        public static Configuration Load()
        {
            Configuration result;
            try
            {
                string configurationPathFileName = GetConfigurationPathFileName();
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(Configuration));
                using (System.IO.FileStream fileStream = new System.IO.FileStream(configurationPathFileName, System.IO.FileMode.Open))
                {
                    XmlReader xmlReader = XmlReader.Create(fileStream);
                    result = (Configuration)xmlSerializer.Deserialize(xmlReader);
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Could not load configuration.xml : " + ex.Message, "Configuration load error", 0);
                result = null;
            }
            return result;
        }
        public static XmlDocument GetConfigurationXmlDocument()
        {
            if (_doc == null)
            {
                _doc = new XmlDocument();
                _doc.Load(GetConfigurationPathFileName());
            }
            return _doc;
        }
        public static XmlNode GetConfigurationNode(string xPathToNode)
        {
            if (_nsmgr == null)
            {
                _nsmgr = new XmlNamespaceManager(GetConfigurationXmlDocument().NameTable);
                _nsmgr.AddNamespace("ns", "http://skynet.kh.ua/BootstrapperConfiguration.xsd");
            }
            return _doc.SelectSingleNode(xPathToNode, _nsmgr);
        }
        private static string GetConfigurationPathFileName()
        {
            string path = "Configuration.xml";
            return System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), path);
        }
    }
}